import 'package:edu/constants/app_images.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/pages/common/course_rating_summary_widget.dart';
import 'package:edu/pages/common/course_review_list_cell_widget.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_page_logic.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

class EduCourseReviewWidget extends StatelessWidget {
  const EduCourseReviewWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      key: const PageStorageKey('review'),
      slivers: [
        const SliverToBoxAdapter(child: SizedBox(height: 10)),
        SliverToBoxAdapter(
          child: Builder(
            builder: (context) {
              final logic = context.read<EduCoursePageLogic>();
              final summary = logic.courseDetail?.reviewSummary;
              if (summary != null) {
                return CourseRatingSummaryWidget(summary: summary);
              } else {
                return const SizedBox.shrink();
              }
            },
          ),
        ),
        const SliverToBoxAdapter(child: SizedBox(height: 10)),
        _buildMyReview(context),
        const SliverToBoxAdapter(child: SizedBox(height: 10)),
        _buildReviewList(context),
        const SliverToBoxAdapter(child: SizedBox(height: 10)),
      ],
    );
  }

  // 我的评价
  Widget _buildMyReview(BuildContext context) {
    return SliverToBoxAdapter(
      child: Selector<EduCoursePageLogic, bool>(
        selector: (_, logic) => logic.myReview != null,
        builder: (context, v, child) {
          if (v) {
            final logic = context.read<EduCoursePageLogic>();
            return CourseReviewListCellWidget(
              review: logic.myReview!,
              courseId: logic.id,
              isMycourse: false,
              isMyReview: true,
            );
          } else {
            final fontSize = Theme.of(context).textTheme.titleMedium?.fontSize;
            return Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Center(
                    child: TextButton(
                      onPressed: () {
                        final logic = context.read<EduCoursePageLogic>();
                        context
                            .pushNamed<CourseReview?>(
                              AppRouter.kCourseReview,
                              queryParameters: {
                                'course_id': logic.id.toString(),
                                'rating': '5',
                              },
                            )
                            .then((v) {
                              if (v != null) {
                                logic.assignMyReview(v);
                              }
                            });
                      },
                      child: Text(
                        AppStrings.writeReivew,
                        style: TextStyle(fontSize: fontSize),
                      ),
                    ),
                  ),
                  const Spacer(),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  // 评价列表
  Widget _buildReviewList(BuildContext context) {
    return Selector<EduCoursePageLogic, bool>(
      selector: (_, logic) => logic.isReviewEmpty,
      builder: (context, v, child) {
        if (v) {
          return SliverToBoxAdapter(
            child: Center(child: Text(AppImages.noContent)),
          );
        } else {
          return Selector<EduCoursePageLogic, Tuple2<int, bool>>(
            selector: (_, logic) =>
                Tuple2(logic.reviewCount, logic.canLoadMoreReviews),
            builder: (context, v, child) {
              final logic = context.read<EduCoursePageLogic>();
              final canLoadMore = v.item2;
              final reviews = logic.reviews ?? [];
              final itemCount = canLoadMore ? v.item1 + 1 : v.item1;
              return SliverList(
                delegate: SliverChildBuilderDelegate(childCount: itemCount, (
                  context,
                  index,
                ) {
                  final review = index < reviews.length ? reviews[index] : null;
                  final courseId = logic.id;
                  if (review != null) {
                    return CourseReviewListCellWidget(
                      review: review,
                      courseId: courseId,
                      isMycourse: false,
                    );
                  } else {
                    return Center(
                      child: Padding(
                        padding: const EdgeInsets.all(10),
                        child: Builder(
                          builder: (context) {
                            Future.delayed(Duration.zero, () {
                              logic.loadReviews();
                            });
                            return const CupertinoActivityIndicator();
                          },
                        ),
                      ),
                    );
                  }
                }),
              );
            },
          );
        }
      },
    );
  }
}
